package com.ciaojian.bytedance.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.bytedance.auth.ByteDanceTokenProvider;
import com.ciaojian.core.bytedance.ByteDanceMiniConfig;
import com.ciaojian.core.bytedance.ByteDancePayConfig;
import com.ciaojian.core.bytedance.ByteDanceSignUtil;
import com.ciaojian.core.mapper.DyOrderMapper;
import com.ciaojian.core.mapper.DyUserMapper;
import com.ciaojian.core.mapper.UserMapper;
import com.ciaojian.core.model.DyUser;
import com.ciaojian.core.model.User;
import com.ciaojian.core.model.dy.DyOrder;
import com.ciaojian.core.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class ByteDanceOrderService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private DyOrderMapper dyOrderMapper;
    @Resource
    private DyUserMapper dyUserMapper;

    @Autowired
    private ByteDanceTokenProvider byteDanceTokenProvider;


    /**
     * 查看抖音订单  潮剪数据库
     * @param openId
     * @return
     */
    public Result getOrders(String openId) {
        try {

            QueryWrapper<User> openid = new QueryWrapper<User>();
            openid.eq("dy_openid", openId);
            User user = userMapper.selectOne(openid);


            QueryWrapper<DyOrder> dyOrderQueryWrapper = new QueryWrapper<DyOrder>();
            dyOrderQueryWrapper.eq("user_id",user.getId());
            dyOrderQueryWrapper.orderByDesc("add_time");
            dyOrderQueryWrapper.orderByDesc("status");
            List<DyOrder> dyOrders = dyOrderMapper.selectList(dyOrderQueryWrapper);


            QueryWrapper<DyUser> dyUserQueryWrapper = new QueryWrapper<DyUser>();
            dyUserQueryWrapper.eq("openid", openId);
            DyUser dyUser = dyUserMapper.selectOne(dyUserQueryWrapper);
            if (ObjectUtil.isNotNull(dyUser)){
                dyOrderQueryWrapper = new QueryWrapper<DyOrder>();
                dyOrderQueryWrapper.eq("user_id",dyUser.getId());
                List<DyOrder> dyOrdersDyuser = dyOrderMapper.selectList(dyOrderQueryWrapper);
                dyOrders.addAll(dyOrdersDyuser);
            }


            return Result.ok(dyOrders);

        }catch (Exception e){
            return Result.error("系统错误");
        }

    }

    /**
     * 订单详情
     * @param orderId
     * @return
     */
    public JSONObject queryOrder(String orderId) {
        JSONObject param = new JSONObject();
        param.put("order_id", orderId);
        param.put("out_order_no", orderId);
        //定义接收数据
        JSONObject result = new JSONObject();
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN");

        try{

            HttpPost httpPost = new HttpPost(ByteDancePayConfig.QUERY_ORDER);
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity entity = new StringEntity(param.toString(), "UTF-8");

            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);


            long timestamp = System.currentTimeMillis() / 1000;
            String signature = ByteDanceSignUtil.getSignature("POST", "/api/apps/trade/v2/query_order",timestamp, param.toJSONString());

            String sign = " " +
                    ""+ ByteDanceMiniConfig.BYTE_AUTHORIZATION+" " +
                    "appid=\""+ByteDanceMiniConfig.APP_ID+"\"," +
                    "nonce_str=\""+ByteDanceMiniConfig.NONCE_STR+"\"," +
                    "timestamp=\""+timestamp+"\"," +
                    "key_version=\"1\"," +
                    "signature=\""+signature+"\"";

            httpPost.setHeader("Byte-Authorization",sign);
            httpPost.setHeader("Content-Type","application/json");
            httpPost.setHeader("access-token",bytedance_clienttoken);


            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }

            return result;

        }catch (Exception e){
            System.out.println(e.getMessage());
            return result;
        }
    }

    public JSONObject query_item_order_info(String orderId) {

        JSONObject param = new JSONObject();
        param.put("order_id", orderId);
//        param.put("out_order_no", orderId);
        //定义接收数据
        JSONObject result = new JSONObject();
        String bytedance_clienttoken = byteDanceTokenProvider.getBytedanceClienttoken("BYTEDANCE_CLIENTTOKEN_MINI");

        try{

            HttpPost httpPost = new HttpPost(ByteDancePayConfig.QUERY_ITEM_ORDER_INFO);
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity entity = new StringEntity(param.toString(), "UTF-8");

            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);


            long timestamp = System.currentTimeMillis() / 1000;
            String signature = ByteDanceSignUtil.getSignature("POST", "/api/apps/trade/v2/order/query_item_order_info",timestamp, param.toJSONString());

            String sign = " " +
                    ""+ ByteDanceMiniConfig.BYTE_AUTHORIZATION+" " +
                    "appid=\""+ByteDanceMiniConfig.APP_ID+"\"," +
                    "nonce_str=\""+ByteDanceMiniConfig.NONCE_STR+"\"," +
                    "timestamp=\""+timestamp+"\"," +
                    "key_version=\"1\"," +
                    "signature=\""+signature+"\"";

            httpPost.setHeader("Byte-Authorization",sign);
            httpPost.setHeader("Content-Type","application/json");
            httpPost.setHeader("access-token",bytedance_clienttoken);


            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }

            return result;

        }catch (Exception e){
            System.out.println(e.getMessage());
            return result;
        }
    }
}
